<template>
  <div class="form-single-fragment third-party-dlg" style="position: relative">
    <el-form
      ref="form"
      :model="formData"
      class="full-width-input"
      :rules="rules"
      style="width: 100%"
      label-width="80px"
      :size="formItemSize"
      label-position="right"
      @submit.prevent
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="分组名称" prop="OnlineApiGroup.groupName">
            <el-input
              class="input-item"
              v-model="formData.OnlineApiGroup.groupName"
              :clearable="true"
              placeholder="请输入分组名称"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="24">
          <el-form-item label="父级分组" prop="OnlineApiGroup.parentId">
            <el-input-number
              class="input-item"
              v-model="formData.OnlineApiGroup.parentId"
              :clearable="true"
              controls-position="right"
              placeholder="请输入父级分组ID"
            />
          </el-form-item>
        </el-col> -->
      </el-row>
    </el-form>
    <el-row class="no-scroll flex-box menu-box" type="flex" justify="end">
      <el-button :size="formItemSize" :plain="true" @click="onCancel"> 取消 </el-button>
      <el-button type="primary" :size="formItemSize" @click="onSubmit()"> 保存 </el-button>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { FormItemRule, ElMessage } from 'element-plus';
import { Arrayable } from 'element-plus/es/utils/typescript';
import OnlineApiGroupController from '@/api/online/OnlineApiGroupController';
import { DialogProp } from '@/components/Dialog/types';
import { ANY_OBJECT } from '@/types/generic';
import { useThirdParty } from '@/components/thirdParty/hooks';
import { ThirdProps } from '@/components/thirdParty/types';
import { useLayoutStore } from '@/store';
import { OnlineApiGroup } from '@/types/online/script';

const layoutStore = useLayoutStore();

interface IProps extends ThirdProps {
  groupId?: number;
  // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
  dialog?: DialogProp<ANY_OBJECT>;
}

const props = defineProps<IProps>();
const { thirdParams, onCloseThirdDialog } = useThirdParty(props);
const formItemSize = computed(() => {
  return layoutStore.defaultFormItemSize || thirdParams.value.defaultFormItemSize?.value;
});

const form = ref();

const formData = reactive<ANY_OBJECT>({
  OnlineApiGroup: {
    groupId: undefined,
    groupName: undefined,
    parentId: undefined,
  },
});

const formEditApiGroup = reactive<ANY_OBJECT>({
  formFilter: {},
  formFilterCopy: {},
  menuBlock: {
    isInit: false,
  },
  isInit: false,
});

const rules: Partial<Record<string, Arrayable<FormItemRule>>> = {
  'OnlineApiGroup.groupName': [
    {
      required: true,
      message: '请输入分组名称',
      trigger: 'blur',
    },
  ],
  // 先不要了
  // 'OnlineApiGroup.parentId': [
  //   {
  //     type: 'integer',
  //     message: '父级分组ID只允许输入整数',
  //     trigger: 'blur',
  //     transform: (value: string) => Number(value),
  //   },
  // ],
};

const dialogParams = computed(() => {
  return {
    groupId: props.groupId || thirdParams.value.groupId,
  };
});

const isEdit = computed(() => {
  return dialogParams.value.groupId != null && dialogParams.value.groupId !== '';
});

const onCancel = () => {
  if (props.dialog) {
    props.dialog.cancel();
  } else {
    onCloseThirdDialog(false);
  }
};

/**
 * 保存
 */
const onSubmit = () => {
  form.value.validate((valid: boolean) => {
    if (!valid) return;
    if (formData.OnlineApiGroup.groupName == null) {
      ElMessage.error('请求失败，发现必填参数为空！');
      return;
    }

    let params = {
      onlineApiGroupDto: {
        groupId: isEdit.value ? dialogParams.value.groupId : undefined,
        groupName: formData.OnlineApiGroup.groupName,
        // parentId: formData.OnlineApiGroup.parentId,
      },
    };

    let httpCall = isEdit.value
      ? OnlineApiGroupController.update(params)
      : OnlineApiGroupController.add(params);
    httpCall
      .then(res => {
        ElMessage.success('保存成功');
        if (props.dialog) {
          props.dialog.submit(res);
        } else {
          onCloseThirdDialog(true);
        }
      })
      .catch(e => {
        console.warn(e);
      });
  });
};

/**
 * 重置表单数据
 */
const resetFormData = () => {
  form.value.resetFields();
};

/**
 * 获取API分组详细信息
 */
const loadApiGroupData = () => {
  return new Promise((resolve, reject) => {
    if (isEdit.value) {
      if (dialogParams.value.groupId == null) {
        resetFormData();
        reject();
        return;
      }
      let params = { groupId: dialogParams.value.groupId };
      OnlineApiGroupController.view(params)
        .then(res => {
          formData.OnlineApiGroup = { ...res.data };
          resolve(res);
        })
        .catch(e => {
          reject(e);
        });
    } else {
      resolve(null);
    }
  });
};

/**
 * 更新编辑API分组
 */
const refreshFormEditApiGroup = () => {
  loadApiGroupData()
    .then(() => {
      if (!formEditApiGroup.isInit) {
        // 初始化下拉数据
        // console.log('');
      }
      formEditApiGroup.isInit = true;
    })
    .catch(e => {
      console.warn(e);
    });
};

const formInit = () => {
  refreshFormEditApiGroup();
};

onMounted(() => {
  // 初始化页面数据
  formInit();
});
</script>
